const { api } = require('../../../utils/api');

// 工具函数：根据ID查找省市区名称
function getRegionNameById(regionData, provinceId, cityId, districtId) {
  let province = regionData.find(item => item.value === provinceId);
  let city = province && province.children ? province.children.find(item => item.value === cityId) : null;
  let district = city && city.children ? city.children.find(item => item.value === districtId) : null;
  return [
    province ? province.label : '',
    city ? city.label : '',
    district ? district.label : ''
  ].filter(Boolean).join(' ');
}

Page({
  data: {
    addressList: [],
    showPopup: false,
    // 三级联动相关
    regionRange: [[], [], []], // picker数据源
    regionIndex: [0, 0, 0],    // picker选中下标
    regionText: '',            // picker显示文本
    regionData: [],            // 原始省市区树状数据
    detailAddress: '',
    isDefault: false,
    editId: undefined
  },
  // 页面加载
  onLoad() {
    this.getRegionData();
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    
  },


  // 添加新地址
  addAddress() {
    this.setData({
      showPopup: true,
      editId: undefined,
      regionIndex: [0, 0, 0],
      regionText: '',
      detailAddress: '',
      isDefault: false
    });
  },

  // 关闭弹出框
  closePopup() {
    this.setData({
      showPopup: false
    });
  },

  // 获取省市区数据
  async getRegionData() {
    const treeAddressList = await api.treeAddress();
    this.setData({
      regionData: treeAddressList.data
    });
    this.initRegionRange(treeAddressList.data);
    // regionData加载完再加载地址列表
    this.getAddressList();
  },

  // 初始化picker数据
  initRegionRange(regionData) {
    const provinceList = regionData || [];
    const cityList = provinceList[0]?.children || [];
    const areaList = cityList[0]?.children || [];
    this.setData({
      regionRange: [provinceList, cityList, areaList],
      regionIndex: [0, 0, 0],
      regionText: ''
    });
  },

  // picker列切换
  regionColumnChange(e) {
    const { regionRange, regionIndex, regionData } = this.data;
    const column = e.detail.column;
    const value = e.detail.value;
    const newIndex = [...regionIndex];
    newIndex[column] = value;
    // 省变
    if (column === 0) {
      const cityList = regionData[value]?.children || [];
      const areaList = cityList[0]?.children || [];
      this.setData({
        regionRange: [regionData, cityList, areaList],
        regionIndex: [value, 0, 0]
      });
    }
    // 市变
    if (column === 1) {
      const provinceIdx = regionIndex[0];
      const cityList = regionRange[1];
      const areaList = cityList[value]?.children || [];
      this.setData({
        regionRange: [regionRange[0], cityList, areaList],
        regionIndex: [regionIndex[0], value, 0]
      });
    }
    // 区变
    if (column === 2) {
      this.setData({
        regionIndex: [regionIndex[0], regionIndex[1], value]
      });
    }
  },
  // picker选择完成
  regionChange(e) {
    const { regionRange } = this.data;
    const idx = e.detail.value;
    const province = regionRange[0][idx[0]];
    const city = regionRange[1][idx[1]];
    const area = regionRange[2][idx[2]];
    this.setData({
      regionIndex: idx,
      regionText: `${province?.label || ''} ${city?.label || ''} ${area?.label || ''}`
    });
  },

  // 详细地址输入
  inputDetailAddress(e) {
    this.setData({
      detailAddress: e.detail.value
    });
  },

  // 默认地址开关
  switchDefault(e) {
    this.setData({
      isDefault: e.detail.value
    });
  },

  // 设为默认地址
  async setDefault(e) {
    const id = e.currentTarget.dataset.id;
    wx.showLoading({ title: '设置中...' });
    const res = await api.setDefaultAddress(id);
    wx.hideLoading();
    if (res.code == 200) {
      wx.showToast({ title: '设置成功', icon: 'success' });
      this.getAddressList();
    } else {
      wx.showToast({ title: res.message || '设置失败', icon: 'none' });
    }
  },

  // 编辑地址，弹出弹窗并回显
  editAddress(e) {
    const id = e.currentTarget.dataset.id;
    const address = this.data.addressList.find(item => item.id === id);
    // 省市区回显下标
    const { regionData } = this.data;
    let provinceIdx = regionData.findIndex(p => p.value === address.provinces);
    let cityIdx = 0, areaIdx = 0;
    let cityList = [], areaList = [];
    if (provinceIdx > -1) {
      cityList = regionData[provinceIdx].children || [];
      cityIdx = cityList.findIndex(c => c.value === address.cities);
      if (cityIdx > -1) {
        areaList = cityList[cityIdx].children || [];
        areaIdx = areaList.findIndex(a => a.value === address.districts);
      }
    }
    this.setData({
      showPopup: true,
      editId: id,
      regionRange: [regionData, cityList, areaList],
      regionIndex: [provinceIdx > -1 ? provinceIdx : 0, cityIdx > -1 ? cityIdx : 0, areaIdx > -1 ? areaIdx : 0],
      regionText: getRegionNameById(regionData, address.provinces, address.cities, address.districts),
      detailAddress: address.detailAddress,
      isDefault: address.defaultFlag === 1
    });
  },

  // 保存地址（新增/编辑）
  async saveAddress() {
    const { regionText, regionIndex, regionRange, detailAddress, isDefault, editId } = this.data;
    // 省必填校验
    const province = regionRange[0][regionIndex[0]];
    const city = regionRange[1][regionIndex[1]];
    const area = regionRange[2][regionIndex[2]];
    if (!province || !province.value) {
      wx.showToast({
        title: '请选择省份',
        icon: 'none'
      });
      return;
    }
    if (!detailAddress.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      });
      return;
    }
    // 组装数据，市和区可为空
    const addressData = {
      provinces: province.value,
      cities: city && city.value ? city.value : '',
      districts: area && area.value ? area.value : '',
      detailAddress,
      defaultFlag: isDefault ? 1 : 0
    };
    if (editId) addressData.id = editId;
    wx.showLoading({ title: '保存中...' });
    const result = await api.saveAddress(addressData);
    wx.hideLoading();
    if(result.code == 200){
      setTimeout(() => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        this.closePopup();
        this.getAddressList();
      }, 1000);
    }
  },
  async getAddressList() {
    const res = await api.getAddresses();
    if (res.code === 200 && Array.isArray(res.data)) {
      const { regionData } = this.data;
      const addressList = res.data.map(item => ({
        ...item,
        region: getRegionNameById(regionData, item.provinces, item.cities, item.districts)
      }));
      this.setData({ addressList });
    }
  },
  // 删除地址
  async deleteAddress(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          const result = await api.deleteAddress(id);
          wx.hideLoading();
          if (result.code === 200) {
            wx.showToast({ title: '删除成功', icon: 'success' });
            this.getAddressList();
          } else {
            wx.showToast({ title: result.message || '删除失败', icon: 'none' });
          }
        }
      }
    });
  },
});